package com.project.common.screens;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.PixelFormat;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.mysql.jdbc.PreparedStatement;
import com.project.trac.R;

import core.modules.DatabaseConnector;
import core.modules.Institute;

public class Registration extends Institute implements OnClickListener {

	private EditText et_studentID;
	private EditText et_username;
	private EditText et_email;
	private EditText et_password;
	private EditText et_rpassword;
	private EditText et_lastname;
	private EditText et_firstname;

	private Spinner spinner;
	private Button btn_submit;
	private Button btn_clear;
	private AlertDialog.Builder alertdialog;
	private TextView textview;
	private ArrayAdapter<CharSequence> adapter;
	private CheckBox cb_showpassword;

	// trac.users
	private List<String> list_username = new ArrayList<String>();
	private List<Integer> list_studentID = new ArrayList<Integer>();
	List<EditText> list_et = new ArrayList<EditText>();

	// EditText.toString() push to arrayList
	private String USERNAME = "uname";
	private String PASSWORD = "pass";
	private String RPASSWORD = "rpass";
	private String EMAIL = "email";
	private String FIRSTNAME = "fname";
	private String LASTNAME = "lname";
	private int STUDENT_ID = 0;
	private String SPINNER_TEXT = "spinner";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.commons_registration);

		if (getRole() == 0) {
			setTitle("New Faculty Member");
		} else {
			setTitle("New Student");
		}

		// ========== EditText
		et_studentID = (EditText) findViewById(R.id.edit_R_StudentNo);
		et_username = (EditText) findViewById(R.id.edit_R_Username);
		et_email = (EditText) findViewById(R.id.edit_R_Email);
		et_password = (EditText) findViewById(R.id.edit_R_Password);
		et_rpassword = (EditText) findViewById(R.id.edit_R_RepeatPassword);
		et_lastname = (EditText) findViewById(R.id.edit_R_LastName);
		et_firstname = (EditText) findViewById(R.id.edit_R_FirstName);
		
		list_et.add(et_username); 			
		list_et.add(et_password);			
		list_et.add(et_email); 				
		list_et.add(et_firstname);			
		list_et.add(et_lastname);
		list_et.add(et_studentID);

		// ========== Spinner
		spinner = (Spinner) findViewById(R.id.edit_R_course_selector);
		
		TextView textStudentNo = (TextView) findViewById(R.id.text_R_Student);
		TextView textSpinner = (TextView) findViewById(R.id.text_R_spinner);

		if (getRole() == 0) {

			et_studentID.setVisibility(View.GONE);
			textStudentNo.setVisibility(View.GONE);
			textSpinner.setText("Title : ");

			adapter = ArrayAdapter.createFromResource (this, R.array.honorifics, android.R.layout.simple_spinner_item);

		} else {

			et_studentID.setVisibility(View.VISIBLE);
			et_studentID.setHint("0xxxxxx - (0 is included)");
			textStudentNo.setVisibility(View.VISIBLE);
			textSpinner.setText("Course : ");

			adapter = ArrayAdapter.createFromResource (this, R.array.courses, android.R.layout.simple_spinner_item);
		}

		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);

		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> av, View view, int position, long id) {

				if (getRole() == 0) {
					getResources().getStringArray(R.array.honorifics);
					SPINNER_TEXT = av.getItemAtPosition(position).toString();
				} else {
					getResources().getStringArray(R.array.courses);
					SPINNER_TEXT = av.getItemAtPosition(position).toString();
				}

			}
			// ===== unused method
			public void onNothingSelected(AdapterView<?> arg0) {}

		});

		// ========== Buttons
		btn_clear = (Button) findViewById(R.id.clear);	
		btn_clear.setOnClickListener(this);

		btn_submit = (Button) findViewById(R.id.submit);
		btn_submit.setOnClickListener(this);

		// ========== CheckBox
		cb_showpassword = (CheckBox) findViewById(R.id.edit_R_showpassword);
		cb_showpassword.setOnClickListener(this);

		new AsynchronousTask().execute("initialize");

	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {

		case R.id.edit_R_showpassword: {

			if (((CheckBox) cb_showpassword).isChecked()) {
				et_password.setTransformationMethod(null);
				et_rpassword.setTransformationMethod(null);
			} else {
				et_password.setTransformationMethod(new PasswordTransformationMethod());
				et_rpassword.setTransformationMethod(new PasswordTransformationMethod());
			}

			break;
		}

		case R.id.clear: {

			for (EditText et: list_et) {
				et.setText("");
			}

			break;
		}

		case R.id.submit: {

			USERNAME = et_username.getText().toString();
			PASSWORD = et_password.getText().toString();
			RPASSWORD = et_rpassword.getText().toString();
			EMAIL = et_email.getText().toString();
			FIRSTNAME = et_firstname.getText().toString();
			LASTNAME = et_lastname.getText().toString();
			
			if (getRole() == 0) {
				STUDENT_ID = 0;											// sql query fix to avoid NullPointerException
			} else {
				STUDENT_ID = Integer.valueOf(et_studentID.getText().toString());
			}
			
			SPINNER_TEXT = spinner.getSelectedItem().toString(); 		// sql query fix to avoid NullPointerException
			
			if (!isValidEmailFormat(EMAIL)) {
				et_email.setError("invalid email format");
			}
			
			if (!isSamePassword()) {
				et_rpassword.setError("passwords do not match");
			}
			
			if ((noEmptyFields() && isValidEmailFormat(EMAIL) && isSamePassword())) {
				if (!isExistingUser(USERNAME) || !isExistingUID(STUDENT_ID)) {
					new AsynchronousTask().execute("register");
				}
			}
			
			break; 
		}

		default: {
			Log.w("Revert to ", "default");
		}

		}// end switch
	}

	@Override
	public void onAttachedToWindow() {
		super.onAttachedToWindow();
		Window window = getWindow();
		window.setFormat(PixelFormat.RGBA_8888);
	}

	private boolean noEmptyFields() {
		
		for (EditText et: list_et) {
			if (et.getText().toString().length() == 0 ) {
				et.setError("field is required");
			}
		}
		
		if (getRole() == 0) {
			if ((USERNAME.length() == 0) || (PASSWORD.length() == 0) || (EMAIL.length() == 0) ||
			   (FIRSTNAME.length() == 0) || (LASTNAME.length() == 0)) {
					return false;
			}
		} else {
			if ((USERNAME.length() == 0) || (PASSWORD.length() == 0) ||(EMAIL.length() == 0) || 
				(FIRSTNAME.length() == 0) || (LASTNAME.length() == 0) || (String.valueOf(STUDENT_ID).length() == 0)) {
					return false;
			}
		}
		return true;

	}

	private boolean isValidEmailFormat(String email) {
		return email.matches("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
	}

	private boolean isSamePassword() {
		
		if (!PASSWORD.equalsIgnoreCase(RPASSWORD)) {
			return false;
		}
		
		return true;
	}
	
	private boolean isExistingUser(String username) {
		
		for (int i = 0; i <= list_username.size() - 1; i++) {
			
			if (list_username.get(i).equalsIgnoreCase(username)) {
				et_username.setError("username already taken");
				return true;
			}
			
		}
		
		return false;
	}
	
	private boolean isExistingUID(int uid) {

		for (int i = 0; i <= list_studentID.size() - 1; i++) {
			if (list_studentID.get(i) == uid) {
				et_studentID.setError("an ID already exists");
				return true;
			}
		}
		
		return false;
	}
	
	private class AsynchronousTask extends AsyncTask<String, String, String> {

		ProgressDialog progressDialog;
		
		PreparedStatement pps;
		
		boolean success;

		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog = new ProgressDialog(Registration.this);
			progressDialog.setTitle("Please Wait");
			progressDialog.setIcon(android.R.drawable.ic_dialog_info);

			if (getRole() == 0) {
				progressDialog.setMessage("preparing faculty form");
			} else {
				progressDialog.setMessage("preparing student form");
			}

			progressDialog.setIndeterminate(true);
			progressDialog.setCancelable(true);
			progressDialog.show();
		}

		protected String doInBackground(String... args) {
			
			try {
				
				if (args[0].toString().equalsIgnoreCase("initialize")) {
					ResultSet rs = DatabaseConnector.getStatement().executeQuery("SELECT username, studentid FROM users");

					while (rs.next()) {
						
						list_username.add(rs.getString("username"));
						
						if (rs.getString("studentid") != "null"){
							list_studentID.add(rs.getInt("studentid"));
						}
					}
					
					rs.close();
				}
				
				if (args[0].toString().equalsIgnoreCase("register")) {
					
					if (getRole() == 0) {
						pps = (PreparedStatement) DatabaseConnector.getConnection().prepareStatement
						("INSERT INTO users(Username, Password, Email, Title, FirstName, LastName, isStudent) VALUES " 
								+ "(?,?,?,?,?,?,?)");
					
						pps.setString(1, USERNAME);
						pps.setString(2, PASSWORD);
						pps.setString(3, EMAIL);
						pps.setString(4, SPINNER_TEXT);
						pps.setString(5, FIRSTNAME);
						pps.setString(6, LASTNAME);
						pps.setInt(7, 0);
						
						success = true;
					
					} else {
						pps = (PreparedStatement) DatabaseConnector.getConnection().prepareStatement
						("INSERT INTO users(Username, Password, Email, FirstName, LastName, StudentID, Course, isStudent) VALUES " 
								+ "(?,?,?,?,?,?,?,?)");
					
						pps.setString(1, USERNAME);
						pps.setString(2, PASSWORD);
						pps.setString(3, EMAIL);
						pps.setString(4, FIRSTNAME);
						pps.setString(5, LASTNAME);
						pps.setInt(6, STUDENT_ID);
						pps.setString(7, SPINNER_TEXT);
						pps.setInt(8, 1);
						
						success = true;
						
					}
					pps.executeUpdate();
					pps.close();
					
				}
				
			} catch (SQLException e) {
				DatabaseConnector.Logger(getClass(), "doInBackground", e);
			}
			

			return null;
		}

		protected void onPostExecute(String postExecute) {

			progressDialog.dismiss();

			try {
				if (success) {

					textview = new TextView(getApplicationContext());
					alertdialog = new AlertDialog.Builder(Registration.this);
					
					textview.setTextAppearance(getApplication(), R.style.alert_message);
					textview.setGravity(Gravity.CENTER_HORIZONTAL);
					textview.setText("Registration success!");

					alertdialog.setTitle("Information").setIcon(android.R.drawable.ic_dialog_info);
					alertdialog.setCancelable(false);
					alertdialog.setView(textview) 
					.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { 
						public void onClick(DialogInterface dialog, int id) { 
							dialog.dismiss(); 
							finish();
						} 
					}).create().show();	
				}

			} catch (Exception e){
				DatabaseConnector.Logger(getClass(), "onPostExecute", e);
			}
		}
		
	}
}